package com.test.demo.service.impl;

import com.test.demo.domain.UmsAdmin;
import com.test.demo.mapper.UmsAdminMapper;
import com.test.demo.service.UmsAdminService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author 远 chards_
 * @date: 2020-02-25 12:21
 */

@Service
public class UmsAdminServiceImpl implements UmsAdminService {

    @Resource
    private UmsAdminMapper umsAdminMapper;

    @Resource
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    public int insert(UmsAdmin umsAdmin) {
        //初始化用户对象
        initUmsadmin(umsAdmin);
        return umsAdminMapper.insert(umsAdmin);
    }

    @Override
    public UmsAdmin get(String username) {
        Example example=new Example(UmsAdmin.class);
        example.createCriteria().andEqualTo("username",username);
        return umsAdminMapper.selectOneByExample(example);
    }

    @Override
    public UmsAdmin get(UmsAdmin umsAdmin) {
      return   umsAdminMapper.selectOne(umsAdmin);
    }

    @Override
    public int update(UmsAdmin umsAdmin) {
        UmsAdmin oldumsAdmin = get(umsAdmin.getUsername());

        oldumsAdmin.setEmail(umsAdmin.getEmail());
        oldumsAdmin.setNickName(umsAdmin.getNickName());
        oldumsAdmin.setNote(umsAdmin.getNote());
        oldumsAdmin.setStatus(umsAdmin.getStatus());

        return umsAdminMapper.updateByPrimaryKey(oldumsAdmin);
    }

    @Override
    public int modifyPassword(String username, String password) {
        System.out.println("com.funtl.myshop.plus.provider.service--------------");
        UmsAdmin umsAdmin = get(username);
        umsAdmin.setPassword(passwordEncoder.encode(password));
        return umsAdminMapper.updateByPrimaryKey(umsAdmin);
    }

    @Override
    public int modifyIcon(String username, String path) {
        UmsAdmin umsAdmin = get(username);
        umsAdmin.setIcon(path);
        return umsAdminMapper.updateByPrimaryKey(umsAdmin);
    }


    /**
     *  初始化用户对象 {@link UmsAdmin}
     * @param umsAdmin
     */
    private void initUmsadmin(UmsAdmin umsAdmin){
        //初始化创建时间
        umsAdmin.setCreateTime(new Date());
        umsAdmin.setLoginTime(new Date());

        //初始化状态
        if (umsAdmin.getStatus() == null) {
            umsAdmin.setStatus(0);
        }

        //密码加密
        umsAdmin.setPassword(passwordEncoder.encode(umsAdmin.getPassword()));
    }

}

